package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MemberDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.*;
import com.itheima.pojo.Member;
import com.itheima.pojo.Setmeal;
import com.itheima.service.MemberService;
import com.itheima.utils.MD5Utils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 会员服务
 */
@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private MemberDao memberDao;

    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    //保存会员信息
    public void add(Member member) {
        String password = member.getPassword();
        if (password != null) {
            //使用md5将明文密码进行加密
            password = MD5Utils.md5(password);
            member.setPassword(password);
        }
        memberDao.add(member);

        Integer memberId = member.getId();//最后插入的会员id,还需要获取关联的角色id(根据角色名)
        String name = member.getUsername();//调用一个方法,根据角色名查询角色ID
        int userId = memberDao.findUserIdByName(name);


        Map<String, Object> map = new HashMap<>();
        map.put("memberId", memberId);
        map.put("userId", userId);


        memberDao.setUserAndRole(map);
    }

    @Override
    //移动端通过手机号和密码查询登录
    public Member findByTelAndPassword(Map map) {
        return memberDao.findByTelAndPassword(map);
    }

    //根据月份查询会员数量
    public List<Integer> findMemberCountByMonths(List<String> months) {//2018.05
        List<Integer> memberCount = new ArrayList<>();
        for (String month : months) {
            String date = month + ".31";//2018.05.31
            Integer count = memberDao.findMemberCountBeforeDate(date);
            memberCount.add(count);
        }
        return memberCount;
    }
    @Override
    public void updateMember(Member member) {
        memberDao.updateMember(member);
    }


    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //每页分页数
        Integer pageSize = queryPageBean.getPageSize();
        //当前页数
        Integer currentPage = queryPageBean.getCurrentPage();
        //查询条件
        String queryString = queryPageBean.getQueryString();
        //将当前页和每页显示条数传给组件
        PageHelper.startPage(currentPage, pageSize);
        //根据条件查询
        Page<Member> members = memberDao.selectByCondition(queryString);


        //调用组建的两个方法,获取总数total和result
        for (Member member : members) {
            //利用会员Id查询对应的健康管理师的姓名
            String userName = userDao.findUserName(member.getId());
            member.setUsername(userName);
           /* User user = userDao.findUserName(member.getId());
            List<User> userProp = new ArrayList();
            userProp.add(user);
            member.setUserList(userProp);*/

            try {
                int age = getAge(member.getBirthday());           //由出生日期获得年龄***
                // System.out.println("age:"+age);
                member.setAge(age);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        long total = members.getTotal();
        List<Member> result = members.getResult();
        return new PageResult(total, result);

    }

    @Override
    public List<Member> findUserNameList() {

        return memberDao.findUserNameList();


    }

    @Override
    public Member findById(Integer id) {
        Member member = memberDao.findById(id);
        Integer id1 = member.getId();
        member.setUsername(memberDao.findUserName(id1));
        return member;

    }

    @Override
    public void editXXF(Member member) {
        memberDao.edit(member);

        //此处需要获取修改后的管理师姓名,修改管理师和会员关联表,
        String username = member.getUsername();
        int userId = memberDao.findUserIdByName(username);//获取角色id
        Integer memberId = member.getId();//获取会员id

        int result = memberDao.findMemberAndUserCount(memberId);
        if (result > 0){
            memberDao.updateMemberAndUser(memberId, userId);
        }else {
            Map<String, Object> map = new HashMap<>();
            map.put("memberId", memberId);
            map.put("userId", userId);

            memberDao.setUserAndRole(map);
        }


    }

    @Override
    public String delete(Integer id) {
        long count = memberDao.findGroupCountByCheckItemId(id);
        if (count > 0) {
            String mealName = memberDao.findMeal(id);
            return mealName;
        }else{
            memberDao.deleteById(id);
            return null;
        }
    }


    //出生日期字符串转换成日期格式
    public static Date parse(String strDate) throws ParseException {
        if (strDate == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.parse(strDate);
    }

    //计算年龄/**/
    public static int getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();
        if (birthDay == null) {
            return 0;
        }

        /*if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }*/
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            } else {
                age--;//当前月份在生日之前，年龄减一

            }
        }
        return age;
    }


    //报表导出信息
    @Override
    public List<ExportInfo> getMemberInfoData(List<Integer> list) throws Exception {

        List<ExportInfo> exportInfoList = new ArrayList<>();
        //根据memberId查询出,在这个循环内查询所有的值
        for (Integer integer1 : list) {
            ExportInfo exportInfo = new ExportInfo();
            Member member = memberDao.findById(integer1);
            //1姓名,性别,手机号
            exportInfo.setMemberName(member.getName());
            exportInfo.setSex(member.getSex());
            exportInfo.setPhoneNumber(member.getPhoneNumber());

            //2机构地址
            int orderId = 0;
            String address="";
            try {
                orderId = memberDao.findOrderIdById(member.getId());
                address = memberDao.findAddressById(orderId);
            } catch (Exception e) {
                e.printStackTrace();
               address =null;
            }
            exportInfo.setAddress(address);

            //3套餐
            String mealName = memberDao.findMeal(member.getId());
            exportInfo.setMenu(mealName);


            //4检查组,已经获得套餐名称,根据,套餐名称查询检查组名称
            //一个套餐返回的是多个检查组,多个值不能用string做返回值,需要用对象返回,这里收集对象,
            //遍历对象,取出对象名
            int mealId = 0;
            try {
                mealId = memberDao.findMealId(mealName);
            } catch (Exception e) {
                e.printStackTrace();
                exportInfoList.add(exportInfo);
                return exportInfoList;
            }

            //根据套餐id查询检查组id,此处查询出的检查组id多个
            List<CheckGroup> checkGroup = memberDao.findcheckGroup(mealId);//多个检查组对象

            List<String> checkNames = new ArrayList<>();
            for (CheckGroup group : checkGroup) {
                checkNames.add(group.getName());
            }

            exportInfo.setCheckGroup(checkNames);


            //5检查项//获取检查项ID集合
            List<Integer> checkgroupIdList = new ArrayList<>();
            for (String checkName : checkNames) {
                int i = memberDao.findcheckGroupId(checkName);
                checkgroupIdList.add(i);//检查组id集合
            }

            //5遍历检查组id,查找检查项
            Set<String> checkItemName = new HashSet<>();
            for (Integer integer : checkgroupIdList) {
                Set<CheckItem> checkItem = memberDao.findCheckItem(integer);
                for (CheckItem item : checkItem) {
                    String name = item.getName();
                    checkItemName.add(name);
                }
            }
            exportInfo.setCheckItemList(checkItemName);


           /* //5检查项
            for (String s : checkGroupName) {*//*[a,b,c,d] 检查组名字集合*//*
                int groupId = memberDao.findcheckGroupId(s);//检查组ID,查询出检查组id集合
                List<Integer> checkgroupIdList = new ArrayList<>();
                checkgroupIdList.add(groupId);//获取到检查组的id,用这个查询出检查项,一个检查组id对应多个检查项

                //遍历检查组id查出,查出检查项
                List<String> checkItemName = new ArrayList<>();
                for (Integer integer : checkgroupIdList) {
                   List<String> name = memberDao.findCheckItem(integer);
                    for (String s1 : name) {

                        checkGroupName.add(s1);
                    }

                }
                exportInfo.setCheckItemList(checkItemName); //需要返回的值是,检查项的name的集合,
            }*/

            exportInfoList.add(exportInfo);
        }


        return exportInfoList;
    }



    @Override//修改完善用户信息
    public void edit(Member member) {
        memberDao.edit(member);
    }

    @Override//根据输入时间查询
    public List<Setmeal> findByDateAndId(String date1, String date2, Integer id) {
        return memberDao.findByDate(date1,date2,id);
    }


    /*
     * author:苏林
    */

    @Override//完善用户信息
    public void editMemberInfo(Member member) {
        memberDao.edit(member);
    }

    @Override//根据输入时间查询
    public  List<Map<String, String>> findByDateAndTelephone(String startDate, String endDate, String telephone) {
        return memberDao.findByDateAndTelephone(startDate,endDate,telephone);
    }

    @Override//查询预约详细信息
    public Map<String,String> findDetail(Integer orderId) {
        return memberDao.findDetail(orderId);
    }

    @Override//查询所有
    public List<Map<String, String>> findAll(String telephone) {
        return memberDao.findAllDetails(telephone);
    }

}
